/*
 * Copyright 2017 Baiyyy
 * @(#)ColdStorageService.java
 */

package com.byyy.ccts.modules.ysjl.service.impl;

import com.byyy.ccts.core.common.service.impl.CommonServiceImpl;
import com.byyy.ccts.core.message.rocketmq.OAProducer;
import com.byyy.ccts.core.utils.*;
import com.byyy.ccts.core.utils.http.HttpUtils;
import com.byyy.ccts.modules.cc.Global;
import com.byyy.ccts.modules.sys.entity.Log;
import com.byyy.ccts.modules.sys.utils.LogUtils;
import com.byyy.ccts.modules.ysjl.entity.YsjlBanner;
import com.byyy.ccts.modules.ysjl.entity.YsjlJielong;
import com.byyy.ccts.modules.ysjl.entity.YsjlJielongDetail;
import com.byyy.ccts.modules.ysjl.mapper.YsjlJielongMapper;
import com.byyy.ccts.modules.ysjl.service.IYsjlJielongDetailService;
import com.byyy.ccts.modules.ysjl.service.IYsjlJielongService;
import com.byyy.ccts.modules.ysjl.vo.WXMsgVo;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by DELL on 2018-6-13.
 */
@Transactional
@Service("ysjlJielongService")
public class YsjlJielongService extends CommonServiceImpl<YsjlJielongMapper, YsjlJielong> implements IYsjlJielongService {

    private static String WX_API_HOSTNAME = "https://qyapi.weixin.qq.com";
    private static String WX_API_GETTOKEN = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww32355b024bba3ae7&corpsecret=P0_uaPMyinUu3Ed-z85tzzDBYv8xLDJh1rmQvSojLAc";
    private static String WX_API_SENDMSG = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
    private String[] WEEK = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};

    @Autowired
    private IYsjlJielongDetailService ysjlJielongDetailService;

    @Override
    public List<YsjlBanner> queryBanner() {
        return this.baseMapper.queryBanner();
    }

    @Override
    public List<YsjlJielong> queryJielong(String person) {
        Calendar calendar = Calendar.getInstance();
        String day = null;
        List<YsjlJielong> ysjlJielongList = this.baseMapper.queryJielong(person);
        if (ysjlJielongList != null && ysjlJielongList.size() > 0) {
            for (YsjlJielong ysjlJielong : ysjlJielongList) {
                calendar.setTime(ysjlJielong.getDqRiqi());
                day = DateUtils.formatDate(ysjlJielong.getDqRiqi(), "yy-MM-dd");
                ysjlJielong.setRiqi(day + WEEK[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
            }
        }
        return ysjlJielongList;
    }

    @Override
    public List<YsjlJielong> queryMyJielong(String person) {
        Calendar calendar = Calendar.getInstance();
        String day = null;
        List<YsjlJielong> ysjlJielongList = this.baseMapper.queryMyJielong(person);
        if (ysjlJielongList != null && ysjlJielongList.size() > 0) {
            for (YsjlJielong ysjlJielong : ysjlJielongList) {
                calendar.setTime(ysjlJielong.getDqRiqi());
                day = DateUtils.formatDate(ysjlJielong.getDqRiqi(), "yy-MM-dd");
                ysjlJielong.setRiqi(day + WEEK[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
            }
        }
        return ysjlJielongList;
    }

    @Override
    public YsjlJielong queryJielongById(String id) {
        Calendar calendar = Calendar.getInstance();
        YsjlJielong ysjlJielong = this.baseMapper.queryJielongById(id);
        calendar.setTime(ysjlJielong.getDqRiqi());
        ysjlJielong.setRiqi(DateUtils.formatDate(ysjlJielong.getDqRiqi(), Global.PATTERN_YYYYMMMDD));
        return ysjlJielong;
    }

    @Override
    public List<YsjlJielongDetail> queryJielongDetailByPid(String pid) {
        return this.baseMapper.queryJielongDetailByPid(pid);
    }

    @Override
    public String jielong(String id, List<YsjlJielongDetail> ysjlJielongDetailList) {
        YsjlJielong jielong = null;
        YsjlJielongDetail detail = null;
        YsjlJielongDetail detailToDel = null;
        int maxNo = 0;
        jielong = ((YsjlJielongMapper)this.baseMapper).queryJielongById(id);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(jielong.getDqRiqi());
        StringBuilder content = (new StringBuilder()).append(DateUtils.formatDate(jielong.getDqRiqi(), new Object[] { Global.PATTERN_YYYYMMMDD })).append("日").append(this.WEEK[calendar.get(Calendar.DAY_OF_WEEK) - 1]).append(jielong.getLocation()).append("场地,").append(((YsjlJielongDetail)ysjlJielongDetailList.get(0)).getPerson()).append(":");
        List<YsjlJielongDetail> existsDetailList = null;
        for (int i = 0; i < ysjlJielongDetailList.size(); i++) {
            detail = ysjlJielongDetailList.get(i);
            detail.setPid(id);
            if (StringUtils.isNotEmpty(detail.getId())) {
                if (StringUtils.isEmpty(detail.getJielongName())) {
                    detailToDel = (YsjlJielongDetail)this.ysjlJielongDetailService.selectById(detail.getId());
                    content.append(detailToDel.getJielongName()).append("(删);");
                    this.ysjlJielongDetailService.deleteById(detail.getId());
                } else {
                    content.append(detail.getJielongName()).append("(更);");
                    this.ysjlJielongDetailService.updateById(detail);
                }
            } else if (!StringUtils.isEmpty(detail.getJielongName())) {
                existsDetailList = ((YsjlJielongMapper)this.baseMapper).queryJielongDetailByPid(id);
                if (existsDetailList != null && existsDetailList.size() > 0) {
                    maxNo = ((YsjlJielongMapper)this.baseMapper).queryMaxDetailNoByPid(id);
                } else {
                    maxNo = 1;
                }
                detail.setNo(maxNo + 1);
                content.append(detail.getJielongName()).append("(增);");
                this.ysjlJielongDetailService.insert(detail);
            }
        }
        OAProducer oAProducer = (OAProducer) SpringContextHolder.getBean("oAProducer");
        ysjlJielongDetailList = ((YsjlJielongMapper)this.baseMapper).queryJielongDetailByPid(id);
        if (ysjlJielongDetailList == null || ysjlJielongDetailList.size() < 1) {
            oAProducer.send("badminton", "badminton", content.append("共接龙").append(ysjlJielongDetailList.size()).append("人").toString());
            return null;
        }
        for (int j = 0; j < ysjlJielongDetailList.size(); j++)
            ((YsjlJielongDetail)ysjlJielongDetailList.get(j)).setNo(j + 1);
        this.ysjlJielongDetailService.updateBatchById(ysjlJielongDetailList);
        oAProducer.send("badminton", "badminton", content.append("共接龙").append(ysjlJielongDetailList.size()).append("人").toString());
        return null;
    }

    @Override
    public String fabuJielong(YsjlJielong ysjlJielong) {
        ysjlJielong.setDqRiqi(DateUtils.toDate(ysjlJielong.getRiqi(), Global.PATTERN_YYYYMMMDD));
        ysjlJielong.setFaqiDate(new Date());
        this.insert(ysjlJielong);
        return null;
    }

    /**
     * 发送消息
     * @param content
     * @return
     */
    private String sendMsg(String content) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        String token = null;
        String res = null;
        int code = 0;

        try {
            // 先判断是否存在token
            token = (String) CacheUtils.get("wx.token");
            if (StringUtils.isEmpty(token)) {
                res = HttpUtils.getHttps(WX_API_HOSTNAME, WX_API_GETTOKEN);
                if (StringUtils.isNotEmpty(res)) {
                    rootNode = mapper.readTree(res);
                    token = rootNode.path("access_token").textValue();
                    CacheUtils.put("wx.token", token);
                }
            }

            // 再组装消息发送
            WXMsgVo vo = new WXMsgVo();
            WXMsgVo.TextMsg msg = new WXMsgVo.TextMsg();
            vo.setAgentid("1000003");
            vo.setMsgtype("text");
            vo.setTouser("@all");
            msg.setContent(content);
            vo.setText(msg);

            res = HttpUtils.httpsPostWithJson(WX_API_HOSTNAME, WX_API_SENDMSG + token, mapper.writeValueAsString(vo));
            if (StringUtils.isNotEmpty(res)) {
                rootNode = mapper.readTree(res);
                code = rootNode.path("errcode").intValue();
                if (0 != code) {
                    logger.error("发送消息失败:" + rootNode.path("errmsg").textValue());
                }
            }
        }
        catch (Exception e) {
            logger.error("发送消息失败！", e);
        }
        return null;
    }

    /**
     * 异步发送消息
     */
    public static class SendMsgThread implements Runnable {

        private String content;

        public SendMsgThread(String content) {
            this.content = content;
        }

        @Override
        public void run() {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = null;
            String token = null;
            String res = null;
            int code = 0;

            try {
                // 先判断是否存在token
                token = (String) CacheUtils.get("wx.token");
                if (StringUtils.isEmpty(token)) {
                    res = HttpUtils.getHttps(WX_API_HOSTNAME, WX_API_GETTOKEN);
                    if (StringUtils.isNotEmpty(res)) {
                        rootNode = mapper.readTree(res);
                        token = rootNode.path("access_token").textValue();
                        CacheUtils.put("wx.token", token);
                    }
                }

                // 再组装消息发送
                WXMsgVo vo = new WXMsgVo();
                WXMsgVo.TextMsg msg = new WXMsgVo.TextMsg();
                vo.setAgentid("1000003");
                vo.setMsgtype("text");
                vo.setTouser("@all");
                msg.setContent(content);
                vo.setText(msg);

                res = HttpUtils.httpsPostWithJson(WX_API_HOSTNAME, WX_API_SENDMSG + token, mapper.writeValueAsString(vo));
                if (StringUtils.isNotEmpty(res)) {
                    rootNode = mapper.readTree(res);
                    code = rootNode.path("errcode").intValue();
                    if (0 != code) {
                        logger.error("发送消息失败:" + rootNode.path("errmsg").textValue());
                    }
                }
            }
            catch (Exception e) {
                logger.error("发送消息失败！", e);
            }
        }
    }
}
